package br.com.puertorico.mecanismos.ui.converters;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

/**
 * Respons&aacute;vel pela remo&ccedil;&atilde;o e insers&atilde;o da
 * m&aacute;scara no valor do Telefone.
 *
 * @author <a href="mailto:daniel.camargo@ufms.br">Daniel Camargo</a>
 * @version $id$
 */
public class TelefoneConverter implements Converter {

	/**
	 * {@inheritDoc}
	 */
	public Object getAsObject(FacesContext ctx, UIComponent ui, String value) {
		if (value == null || value.trim().length() == 0) {
			return null;
		}
		return value.replaceAll("[^\\d]", "");
	}

	/**
	 * {@inheritDoc}
	 */
	public String getAsString(FacesContext ctx, UIComponent ui, Object value) {
		if (value == null || value.toString().isEmpty()) {
			return null;
		}
		String telefone = value.toString();

		if (telefone.length() > 7 && telefone.substring(0, 4) == "0800") {
			return telefone
					.replaceAll("^(\\d{4})(\\d{3})(\\d{4})$", "$1-$2-$3");
		}
		return telefone.replaceAll("^(\\d{2})(\\d{4})(\\d{4})$", "($1) $2-$3");
	}
}